package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.schema.property.ObjectMapperBeanPropertyNamingStrategy;

import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Validated
@Api(tags = "02.微博模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    // 自动装配redisTemplate[从IoC容器中获取的Bean对象,因为创建过配置类,所以IoC容器中才会存在此Bean对象]
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
    @Autowired
    private ObjectMapperBeanPropertyNamingStrategy objectMapperBeanPropertyNamingStrategy;

    /**
     * 1.发布微博功能
     */
    @ApiOperation("发布微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session){
        /*
            1.接收客户端传递的数据;
            2.校验用户登录状态:session.getAttribute("user");
              2.1 未登录状态: return 2;
              2.2 登录状态: 微博表中插入数据[INSERT接口], return 1;
         */
        log.debug("weiboDTO = " + weiboDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        // 登录状态校验已在拦截器中实现
        // 登录状态,发布成功
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());

        weiboMapper.insert(weibo);

        return JsonResult.ok();
    }

    /**
     * 2.微博首页列表
     */
    @ApiOperation("微博首页列表")
    @GetMapping("selectIndex")
    public JsonResult selectIndex() throws JsonProcessingException {
        /*
            Redis中key-value: {"weibo_index": 具体首页数据}
            1.确认缓存[Redis]中是否存在首页数据;
            2.缓存中存在,直接返回;
            3.缓存中不存在,查询数据库,将数据保存到缓存[redis]中,返回;
         */
        // opsForValue: 创建操作字符串类型的对象ops
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable weiboIndex = ops.get("weibo_index");
        if (weiboIndex == null){
            //缓存中不存在,查询数据库,将数据保存到缓存[redis]中,返回;
            List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
            //Jackson: 序列化和反序列化的库;
            //将Java对象[List集合weiboIndexVOS]序列化为JSON格式之后,再存入Redis数据;
            ObjectMapper objectMapper = new ObjectMapper();
            String indexJson = objectMapper.writeValueAsString(weiboIndexVOS);
            //存入Redis
            ops.set("weibo_index", indexJson, 30, TimeUnit.SECONDS);
            System.out.println("首页数据来自MYSQL数据库");
            return JsonResult.ok(weiboIndexVOS);
        }
        // 缓存中存在,直接返回;
        System.out.println("首页数据来自Redis缓存");
        // 反序列化：将JSON格式的数据转换为Java对象[List集合]
        ObjectMapper objectMapper = new ObjectMapper();
        List<WeiboIndexVO> indexVOList = objectMapper.readValue(weiboIndex.toString(), List.class);

        return JsonResult.ok(indexVOList);
    }

    /**
     * 3.微博详情功能
     */
    @ApiOperation("微博详情")
    @GetMapping("selectById")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "微博编号", required = true, dataType = "int", example = "200"),
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "string")
    })
    public JsonResult selectById(@Range(min = 100, max = 500, message = "微博ID必须在100-500之间") @RequestParam int id, String username){
        // 手动抛出异常,用于全局异常处理器接收并处理该异常
        if (id < 0) {
            throw new IllegalArgumentException("微博ID不能小于0");
        }

        //username参数没有其他作用,只是为了Knife4j文档描述说明
        log.debug("id = " + id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        log.debug("weiboDeatilVO = " + weiboDetailVO);

        return JsonResult.ok(weiboDetailVO);
    }
}









